
<template>
  <div class="home">
<!--    socket.io + vue-socket.io 方式实现群聊私聊（未实现）-->
    <div class="input-session">
      <el-container>
        <el-header>
          <!--          头部内容显示-->
          <header-com :nickName="this.$route.params.nickName" :headImage="headImage" @outLogin="getOut"/>
        </el-header>
        <el-container>
          <el-aside>
            <!--            好友列表显示-->
            <friends-list @choose="chooseMeth"  />
          </el-aside>
          <el-main v-if="chooseRoom != ''" style="position:relative;">
            <!--            聊天内容显示-->
            <div id="assPCon" style="width:100%;height: 70%;display:block;overflow-y:auto;">
              <div v-for="dataList in datas">
                <div class="friend" v-if="dataList.accountNum != accountNum">
                  <div class="leftPhot">
                    <el-avatar :src="'http://42.193.17.196:8089/Images/'+dataList.hImage"/>
                  </div>
                  <div class="rightMsg">
<!--                    <span>{{dataList.userName}}</span>-->
                    <div style="left: 0.4rem;">
                      {{dataList.date}}
                    </div>
                    <div style="color:#4F779C;" >

                      {{ dataList.content }}
                    </div>
                  </div>
                </div>
                <div v-else style="width: 99%;height: 70px;">
                  <div style="float: right;">
<!--                    <div>{{dataList.userName}}</div>-->
                    <div class="friend">
                      <div class="rightMsg" style="text-align:right;margin-right: 10px;">
                        <div>
                          {{dataList.date}}
                        </div>
                        <div style="background-color: #12B7F5;">
                          {{ dataList.content }}
                        </div>

                      </div>
                      <div class="leftPhot">
                        <el-avatar :src="'http://42.193.17.196:8089/Images/'+headImage"/>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!--富文本编辑器-->
            <div style="margin-top: 1rem;">
              <textarea id="textareaDate" v-model="chatContent" @keyup.enter="sendOut" style="width:100%;height: 150px"
                        placeholder="请输入内容"/>
              <div>
<!--                表情按钮-->
                <el-popover
                    placement="bottom"
                    trigger="manual"
                    v-model="visible">
                  <VEmojiPicker solt="content" v-show="showEmojiDialog" @select="selectEmoji"/>
                  <img src="../assets/emoji.png" style="width:30px;float:left;" slot="reference" @click="clickEmoji" />
                </el-popover>
<!--                语音按钮-->
                  <div>
                    <img  style="width:30px;float:left;margin-left: 10px;" src="../assets/语音.png" />
                  </div>
<!--                视频按钮-->
                 <div>
                   <img style="width:30px;float:left;margin-left: 10px;" src="../assets/视频通话.png" />
                 </div>

                <button type="primary" @click="sendOut" class="sendBtn">发送</button>
              </div>
            </div>
          </el-main>
          <el-main v-else>
            欢迎使用Y - IM
          </el-main>
        </el-container>
      </el-container>


    </div>
  </div>
</template>
<script src="../../../../../socketIOServer.js"></script>
<script>

import headerCom from '@/components/header'
import friendsList from '@/components/friendsList'
import {mapState} from 'vuex'
import {ACCOUNT_NUM,} from "../store/mutationTypes";
import webStore from "../store/webStore";
import {formatDate,anyToString} from "../../lib/utils";
import {VEmojiPicker} from 'v-emoji-picker'
export default {
  name: 'HomeIO',
  components: {
    headerCom,
    friendsList,
    VEmojiPicker
  },

  computed:{
    ...mapState({
      'accountNum':state=>state.webStore.Config.ACCOUNT_NUM,
      'chooseRoom':state=>state.webStore.Config.SELECT_FRIENDS,
    }),
  },
  data() {
    return {
      visible:false,
      showEmojiDialog:false,
      // images: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
      chatContent: "",//需要发送的内容
      sendMsgArray: [],//发送的消息数组
      receiveMsgArray: [],//接收的消息数组
      datas: [],
      headImage:"",
      // contentList:[],//保存所有好友的最近一条信息
      timingSocketPush:"",
      editorOption: {// 富文本框参数设置
        modules: {   //modules为自定义标题栏，使用默认的话可去掉modules
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],//分别对应的是： 粗体，斜体，下划线，删除线
            ['code-block'], ////引用，代码块
            [{'header': 1}, {'header': 2}],
            ["clean"], //清除字体样式
            ["image"], //上传图片、上传视频
          ]
        }
      },
    }
  },
  created() {
    this.headImage = this.$route.params.headImage;
  },
  beforeDestroy() {
    //关闭链接
    //取消订阅事件（否则下次订阅消息会接收多条）
    // this.sockets.unsubscribe(eventName)
  },
  sockets:{
    onlineNotification(onlineData){
      this.$notify({
        title: '通知',
        message: onlineData,
        offset: 100,
        position: 'top'
      });
    },
    disconne(outData){
      this.$notify({
        title: '通知',
        message: outData,
        offset: 100,
        position: 'top'
      });
      this.$router.push("/")
    },
    sendMessage(msg){

      this.datas = [];
      Object.assign(msg,{date:formatDate(new Date(),true)})

      let sendMsg = JSON.parse(sessionStorage.getItem("sendMsg"));

      let getMsg = sendMsg;
      getMsg.push(msg);
      sessionStorage.setItem("sendMsg",JSON.stringify(getMsg))

      for(let value of sendMsg){
        //①自己发的消息 ②界面在选中发送消息的好友界面（发送方）
        // 结果：可显示本条消息在界面
        if(value.accountNum === this.accountNum.toString() && value.chooseRoom.toString() === this.chooseRoom.toString() ){
          this.datas.push(value)
        }
        //①别人发的消息 ②接收人就是当前登录的人 ③发送消息的人就是当前登录人选中的好友（接收方）
        // 结果：可显示本条消息在界面
        else if(value.accountNum !== this.accountNum.toString() && value.chooseRoom.toString() === this.accountNum.toString() && value.accountNum === this.chooseRoom.toString()){
          this.datas.push(value)
        }
        //①别人发的消息 ②接收人也不是当前登录的人 ③当前选中的好友就是接收人（群聊）
        // 结果：可显示本条消息在界面
        else if(value.accountNum !== this.accountNum.toString() && value.chooseRoom.toString() !== this.accountNum.toString()  && value.chooseRoom.toString() === this.chooseRoom.toString()){
          this.datas.push(value)
        }

      }
      //自动定位到最新信息
      const div = document.getElementById('assPCon');
      if(div !== null){
        this.$nextTick(() => {
          div.scrollTop = div.scrollHeight;
        })
      }
      document.addEventListener('AnimationEnd', ()=>{
        //动画结束后执行操作
      })
    },

  },

  mounted() {
    sessionStorage.setItem("sendMsg",JSON.stringify(this.datas))
    if(this.accountNum === ""){
      this.$router.push("/")
      return
    }
    let userOK = {"nickName": this.$route.params.nickName,"accountNum":this.accountNum};
    this.$socket.emit("login",anyToString(userOK))

  },
  methods: {
    clickEmoji(){
      this.visible = true;
      this.showEmojiDialog = true;
    },
    selectEmoji(emoji) {// 选择emoji后调用的函数
      let input = document.getElementById("textareaDate")
      let startPos = input.selectionStart
      let endPos = input.selectionEnd
      let resultText = input.value.substring(0, startPos) + emoji.data + input.value.substring(endPos)
      input.value = resultText
      input.focus()
      input.selectionStart = startPos + emoji.data.length
      input.selectionEnd = startPos + emoji.data.length
      this.chatContent = resultText;
      this.visible = false;
      this.showEmojiDialog = false;
    },
    chooseMeth(chooseBool){
      if(chooseBool === "change"){
        this.datas = [];
      }else if(chooseBool === "haveSessMsg"){
       let msg = JSON.parse(sessionStorage.getItem("sendMsg"));
        for(let value of msg){
          //①自己发的消息 ②界面在选中发送消息的好友界面（发送方）
          // 结果：可显示本条消息在界面
          if(value.accountNum === this.accountNum.toString() && value.chooseRoom.toString() === this.chooseRoom.toString() ){
            this.datas.push(value)
          }
          //①别人发的消息 ②接收人就是当前登录的人 ③发送消息的人就是当前登录人选中的好友（接收方）
          // 结果：可显示本条消息在界面
          else if(value.accountNum !== this.accountNum.toString() && value.chooseRoom.toString() === this.accountNum.toString() && value.accountNum === this.chooseRoom.toString()){
            this.datas.push(value)
          }
          //①别人发的消息 ②接收人也不是当前登录的人 ③当前选中的好友就是接收人（群聊）
          // 结果：可显示本条消息在界面
          else if(value.accountNum !== this.accountNum.toString() && value.chooseRoom.toString() !== this.accountNum.toString()  && value.chooseRoom.toString() === this.chooseRoom.toString()){
            this.datas.push(value)
          }
        }
        console.log("datas数据恢复：：",this.datas)
      }
    },
    // //点击发送信息按钮
    sendOut() {
      let data = {"chatContent": this.chatContent, "accountNum": this.accountNum,"headImages":this.headImage,"chooseRoom":this.chooseRoom};
      this.$socket.emit("message",anyToString(data))
      this.chatContent = "";
    },
    //退出
    getOut(Outdata){
      let userOK = {"accountNum":this.accountNum};
      this.$socket.emit("outConn",anyToString(userOK))
    },

  },

}
</script>

<style lang="less" scoped>
@width:100%;
@height:100%;
html,
body {
  width: @width;
  height: @height;
  padding: 0;
  margin: 0;
  color: #eee;
  background-color: black;
  .home{
    .ql-editor {
      height: 70px;
    }
    .input-session {
      height: 19%;
      width: @width;
      border: #eee 1px solid;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .el-header {
        background-color: #B3C0D1;
        padding:0;
      }

      .el-aside {
        width: 20%;
        background-color: #D3DCE6;
      }

      .el-main {
        width: 70%;
        height: 670px;
        background-color: #E9EEF3;
        //@keyframes mymove
        //{
        //  from {opacity: 1;}
        //  to {opacity: 0;}
        //}
        .friend {
          width: @width;
          height: 60px;
          //animation:mymove 5s infinite;
          //animation-fill-mode:forwards;
          //animation-iteration-count:1;/*动画只执行一次*/

          .leftPhot {
            float: left;
            vertical-align: middle;
          }
        }

        .rightMsg {
          position:relative;
          text-align: left;
          margin-left: 0.5rem;
          font-size: 11px;
          color: #686868;
          float: left;
          display: block;
          min-height: 20px;
          margin-top: 1rem;
          div:nth-child(1){
            position: absolute;
            width: 130px;
            right: 0.4rem;
            top: -1rem;
          }
          div:nth-child(2) {
            font-size: 15px;
            border-radius: 10px;
            background-color: #A7EAF8;
            line-height: 30px;
            text-indent: 1rem;
            color: #fff;
            padding-right: 1rem;
          }

          div:nth-child(3) {
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
          }
        }


        .sendBtn {
          width: 100px;
          height: 30px;
          background-color: blue;
          color: #fff;
          border: 0;
          float: right;
          border-radius: 4px;
          cursor: pointer;
        }


      }
    }
  }
}

















</style>
